package web.day02;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoAccessLog extends HttpServlet {
	//定义全局变量
	private BufferedWriter writer;
    private DateFormat formatter;
    

    @Override
    public void init() throws ServletException {
   
//	String logFile=config.getServletConfig("logFile");
//	String dateFormat=config.getServletConfig("dateFormat");
    	
    	//读取当前的servlet的初始化参数
      ServletConfig config=getServletConfig();
      String logFile=config.getInitParameter("logFile");
      String dateFormat=config.getInitParameter("dateFormat");
      
      //读取全局的servlet初始化参数
//      ServletContext context=getServletContext();
//      String logFile=context.getInitParameter("logFile");
//      String dateFormat=context.getInitParameter("dateFormat");
      
      try {
      //true为追加内容
      writer=new BufferedWriter(new FileWriter(logFile,true));
      }catch(IOException e) {
    	  e.printStackTrace();
      }
      
      formatter=new SimpleDateFormat(dateFormat);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	ServletContext context=getServletContext();
    	System.out.println("context:"+context);
    	System.out.println("count");
    	
    	//获取客户端的IP地址
    	System.out.println(req.getRemoteAddr());
    	Date date=new Date();
    	System.out.println(date);
    	System.out.println("有人访问了");
    	
    	String content=req.getLocalAddr()+"\t"+formatter.format(date);
    	
    	logFile(content);
    }
	private void logFile(String content) {
		//同步
		synchronized (this) {
			
			try {
				writer.write(content);
				writer.write("\n");
				writer.flush();//强制写入
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			
		}
		
	}
	@Override
	public void destroy() {
		if(writer!=null) {//判断是否为空
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
